﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SaiLing.SingleSignOn.Application.Core.DataTransferObject.System
{
    public class TreeNode
    {
        public Guid Id { get; set; }

        public Guid ParentId { get; set; }
        public string Text { get; set; }

        public int Sort { get; set; }

        public List<TreeNode> ChildrenList { get; set; }
        
    }

    public static class TreeHelper
    {
        public static List<TreeNode> ToTree(this List<TreeNode> source, List<TreeNode> result, Guid? parentId, int? deep = null)
        {
            if (source == null)
                return null;
            if (result == null)
                result = new List<TreeNode>();
            var root = source.Where(x => x.ParentId == parentId).ToList().OrderBy(x => x.Sort);
            string deepString = "";
            if (deep.HasValue)
                deepString = GetDeepString(deep.Value);
            foreach (var node in root)
            {
                node.Text = deepString + node.Text;
                // if (node.ParentId == Guid.Empty)
                result.Add(node);
                var children = source.Where(x => x.ParentId == node.Id).ToList();
                if (children.Any())
                {
                    //node.ChildrenList = children;
                    source.ToTree(result, node.Id, deep.HasValue ? ((int?)(deep.Value + 1)) : null);
                }
            }
            return result;
        }

       

        public static string GetDeepString(int deep)
        {
            var deepStr = new StringBuilder();
            for (var i = 0; i < deep; i++)
            {
                deepStr.Append("　");
            }
            if (deep != 0)
            {
                deepStr.Append("├─");
            }
            return deepStr.ToString();
        }


    }
}
